import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse } from '@angular/common/http';
// import { Observable } from 'rxjs/observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
import { Observable } from 'rxjs/Rx'


@Injectable()
export class HttpInterceptorProvider implements HttpInterceptor {

  constructor() {
  }
  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    // 请求失败拦截器
    return next
      .handle(req)
      .map((event: any) => {
        if (event instanceof HttpResponse) {
          console.log(event);
        }
        return event;
      })
      .catch((res: HttpResponse<any>) => {
        switch (res.status) {
          case 401:
            // 错误
            break;
          case 405:
            // 错误
            alert('错误');
            break;
          case 404:
            alert('404');
            break;
        }
        // 以错误的形式结束本次请求
        return Observable.throw(res);
      })
  }
}
